package com.eastcode.mobile.server.interceptor;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.eastcode.mobile.server.system.entity.User;
import com.eastcode.mobile.server.util.ServerConstant;

public class LoginFilter implements Filter {

	Logger log = Logger.getLogger(this.getClass().getName());

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(true);
		User user = (User) session.getAttribute(ServerConstant.SYS_USER);

		String cmd = request.getParameter("cmd");

		if (!("login".equals(cmd) || "regist".equals(cmd))) {
			if (user == null || user.getUserId() == null) {
				request.getRequestDispatcher("/template/login.ftl").forward(request, response);
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
